; wutil.asm
; Window utilities

	.include "common.inc"
	.include "global.inc"
	.include "window.inc"
	.include "execfun.inc"
	.include "text.inc"

	.export addclsbtn
	.export getemsize
	.export getmousrel
	.export btncheck

	.segment "RODATA"
	
tx_pic:		.byte 13, $42, $0C, $09, $0E, $0B, $05, $0E, $0C, $09, $07, $08, $14, $13
tx_any:		.byte 6, $56, $09, $03, $2D, $32, $30

	BC_LEFT = 1
	BC_TOP = 1
	BC_WIDTH = 7
	BC_HEIGHT = 7

b_close:	.byte %01111100, %10111010, %11010110, %11101110
			.byte %11010110, %10111010, %01111100
bm_close:	.byte BC_WIDTH, BC_HEIGHT
			.word b_close
tx_close:	.byte $FF
			.word bm_close

em:			.byte 1, $4D	; 'M'

	.segment "CODE"

;
;	Adds a close button to a window ("X")
;	INPUT:
;		A .. window index
;

addclsbtn:	jsr win_create
			lda #WSTYLE_BCKGND
			jsr win_setstyle
			ldx #BC_LEFT
			ldy #BC_TOP
			jsr win_setpos
			ldx #BC_WIDTH
			ldy #BC_HEIGHT
			jsr win_setdim
			lda #<tx_close
			ldx #>tx_close
			jsr win_settext
			lda #WTYPE_BUTTON
			jsr win_settype
			lda #<ex_close_win
			ldx #>ex_close_win
			jmp win_setexec

; Button exec handler for close button
ex_close_win:
			jsr ex_button
			ldy #Event::type
			lda (reg2), y
			cmp #EVT_MOUSE_UP
			beq @close
			rts
@close:		jsr win_getfrm
			jsr frm_destroy
			rts
;
;	Gets size of "M" for a given font
;	INPUT:
;		A .. font no.
;	OUTPUT:
;		X/Y .. emsize in pixel
;
getemsize:	jsr t_font
			lda #<em		; get em size
			ldx #>em
			jmp t_getextent

;
;	Gets relative position for mouse event
;	INPUT:
;		(reg2) ... Mouse event
;		current window (has frame!)
;	OUTPUT:
;		X/Y ... relative position
;

getmousrel:	jsr win_getfrm			; get frame origin
			jsr frm_getpos
			stx winx
			sty winy
			ldy #MouseEvent::mx		; calc rel. x
			lda (reg2), y
			sec
			sbc winx
			tax
			ldy #MouseEvent::my
			lda (reg2), y
			sec
			sbc winy
			tay
			rts

;
; Checks if current event is button down and pops return
; address if true.
;

btncheck:	jsr ex_button
			ldy #Event::type
			lda (reg2), y
			cmp #EVT_MOUSE_UP
			beq @btndown
			pla						; pop return address
			pla
@btndown:	rts


	.segment "DATA"

winx:		.byte 0
winy:		.byte 0
